package m.member.order.service;

import com.alibaba.fastjson.JSONObject;
import flow.model.FlowItemPhase;
import m.common.action.VueResult;
import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.member.manage.model.MemberInfo;
import m.member.manage.service.AppSettingService;
import m.member.manage.service.inter.MoneyRecordInter;
import m.member.order.model.OrderDetail;
import m.member.order.model.OrderInfo;
import m.member.order.util.MoneyRecordUtil;
import m.system.cache.CacheUtil;
import m.system.db.DBManager;
import m.system.db.DataRow;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;
import manage.model.AdminLogin;
import manage.model.OrgGroupView;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class OrderInfoService extends Service implements MoneyRecordInter {
    public String saveAll(OrderInfo model, List<JSONObject> list, AdminLogin admin, OrgGroupView dept) throws Exception {
        ModelCheckUtil.checkNotNull(model,"member.oid","serveAdmin.oid","payType","otherAmount");
        String msg;
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            if (ObjectUtil.isEmptyOid(model)) {
                model.setOid(GenerateID.generatePrimaryKey());
                model.setStatus("A");
                model.setInputAdmin(admin);
                model.setInputDept(dept);
                ModelUpdateUtil.insertModel(model);
                msg="保存成功";
            }else{
                ModelCheckUtil.equals(model,new String[]{"status","inputAdmin.oid"},new Object[]{"A",admin.getOid()},"只有本人录入且未确认的才能修改");
                ModelUpdateUtil.updateModel(model,"member.oid","serveAdmin.oid","payType","payOper","otherAmount","remark");
                msg="修改成功";
            }
            for(JSONObject json : list){
                if(json.getIntValue("deleteFlag")==1){//tableForm存在oid删除时添加的deleteFlag标识，1代表删除
                    ModelUpdateUtil.deleteModel(json.toJavaObject(OrderDetail.class));
                }else{
                    OrderDetail detail=json.toJavaObject(OrderDetail.class);
                    detail.setOrder(model);
                    detail.setServe(ModelQueryList.getModel(detail.getServe(),"*"));
                    detail.setPrice(detail.getServe().getPrice());
                    detail.setDiscount(detail.getServe().getDiscount());
                    detail.setTotal(NumberUtil.round(detail.getPrice()*detail.getNum()*(100-detail.getDiscount())/100.0,2));
                    if(ObjectUtil.isEmptyOid(detail)){
                        detail.setOid(GenerateID.generatePrimaryKey());
                        ModelUpdateUtil.insertModel(detail);
                    }else{
                        ModelUpdateUtil.updateModel(detail);
                    }
                }
            }
            updateOrderAmount(model.getOid());
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        return msg;
    }
    public String save(OrderInfo model, AdminLogin admin, OrgGroupView dept) throws Exception {
        ModelCheckUtil.checkNotNull(model,"member.oid","serveAdmin.oid","payType","otherAmount");
        String msg;
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            if (ObjectUtil.isEmptyOid(model)) {
                model.setOid(GenerateID.generatePrimaryKey());
                model.setStatus("A");
                model.setInputAdmin(admin);
                model.setInputDept(dept);
                ModelUpdateUtil.insertModel(model);
                msg="保存成功";
            }else{
                ModelCheckUtil.equals(model,new String[]{"status","inputAdmin.oid"},new Object[]{"A",admin.getOid()},"只有本人录入且未确认的才能修改");
                ModelUpdateUtil.updateModel(model,"member.oid","serveAdmin.oid","payType","payOper","otherAmount","remark");
                msg="修改成功";
            }
            updateOrderAmount(model.getOid());
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
        return msg;
    }
    public void delete(OrderInfo model,AdminLogin admin) throws Exception {
        ModelCheckUtil.equals(model,new String[]{"status","inputAdmin.oid"},new Object[]{"A",admin.getOid()},"只有本人录入且未确认的才能删除");
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            ModelUpdateUtil.deleteModel(model);//删除整单
            ModelUpdateUtil.deleteModels(//删除明细
                ModelQueryList.getModelList(OrderDetail.class,new String[]{"oid"},null,
                    QueryCondition.eq("order.oid",model.getOid())
                ).toArray(new OrderDetail[0])
            );
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
    }

    /**
     * 更新订单金额
     */
    public void updateOrderAmount(String oid) throws Exception {
        DataRow dr=DBManager.queryFirstRow("select ifnull(sum(total),0) total from to_order_detail where order_oid=?",oid);
        OrderInfo model=ModelQueryList.getModel(OrderInfo.class,oid,"*","member.level.discount");
        int dayRate=getService(AppSettingService.class).getDiscount(model.getInputDate());
        int levelRate=model.getMember().getLevel().getDiscount();
        model.setOrderAmount(dr.get(Double.class,"total"));
        model.setPreferentialAmount(NumberUtil.round(model.getOrderAmount()*levelRate/100.0,2));
        model.setMemberDayAmount(-NumberUtil.round((model.getOrderAmount()-model.getPreferentialAmount()+model.getOtherAmount())*dayRate/100.0,2));
        model.setPayAmount(NumberUtil.round(model.getOrderAmount()-model.getPreferentialAmount()+model.getOtherAmount()+model.getMemberDayAmount()));
        ModelUpdateUtil.updateModel(model,"orderAmount","preferentialAmount","memberDayAmount","payAmount");
    }
    public void submit(OrderInfo model, AdminLogin admin) throws Exception {
        ModelCheckUtil.equals(model,new String[]{"inputAdmin.oid"},new Object[]{admin.getOid()},"只有本人录入的才能提交");
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            model= ModelQueryList.getModel(model,"*");
            if(!"A".equals(model.getStatus())) throw new MException(this.getClass(),"只能提交未提交的记录。");
            if("0".equals(model.getPayType())){
                if(null!=model.getPayOper()&&Arrays.asList(model.getPayOper()).contains("Y")){
                    MemberInfo member= CacheUtil.get(MemberInfo.class,model.getMember().getOid());
                    double creditMoney=NumberUtil.round(model.getPayAmount()-(member.getBalance()-member.getFreeze()));
                    if(creditMoney>0){
                        getService(MemberRechargeService.class).addCredit(model,creditMoney);
                    }
                }
                //充值核算 并更新订单上的数据
                Double[] amounts=getService(RechargeOffsetService.class).create(model.getOid());
                model.setPayRealMoney(amounts[0]);
                model.setPayGiveMoney(amounts[1]);
                model.setStatus("N");
            }else{
                model.setPayRealMoney(model.getPayAmount());
                model.setPayGiveMoney(0d);
                model.setStatus("N");
            }
            ModelUpdateUtil.updateModel(model,"payRealMoney","payGiveMoney","status");
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
    }
    public void back(OrderInfo model) throws Exception {
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            model= ModelQueryList.getModel(model,"*");
            if(!"N".equals(model.getStatus())) throw new MException(this.getClass(),"只能退回未确认的记录。");
            if("0".equals(model.getPayType())) {
                //充值核算删除 并更新订单上的数据
                getService(RechargeOffsetService.class).remove(model.getOid());
            }
            //移除赊账充值，没有则不移除
            getService(MemberRechargeService.class).removeCredit(model.getOid());
            model.setPayRealMoney(null);
            model.setPayGiveMoney(null);
            model.setStatus("A");
            ModelUpdateUtil.updateModel(model,"payRealMoney","payGiveMoney","status");
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
    }
    public void confirm(OrderInfo model, AdminLogin admin, OrgGroupView dept) throws Exception {
        if(ObjectUtil.isEmptyOid(model)) throw new MException(this.getClass(),"业务主键为空");
        ModelCheckUtil.equals(model,new String[]{"inputDept.oid"},new Object[]{dept.getOid()},"店铺不符，不能确认！");
        TransactionManager tm=new TransactionManager();
        try{
            tm.begin();
            model= ModelQueryList.getModel(model,"*");
            if(!"N".equals(model.getStatus())) throw new MException(this.getClass(),"只能确认未确认的记录。");
            model.setConfirmAdmin(admin);
            model.setConfirmDate(new Date());
            model.setStatus("Y");
            ModelUpdateUtil.updateModel(model,"confirmAdmin.oid","confirmDate","status");
            //添加金额记录
            MoneyRecordUtil.addOrder(model);
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
    }

    @Override
    public VueResult toViewPage(String busiOid) {
        return null;
    }
}
